var mainPanel;
var combobox;
var dailyStroe;
var weekStroe;
var monthStroe;
var quarterStroe;
var tabPanelChanged = false;

if (Ext.isIE) {
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-date-trigger { margin-top:-1px  } </style>');
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-trigger { margin-top:-1px  } </style>');
}

function getTopNCombox() {
	var store = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '10', '10名' ], [ '20', '20名' ], [ '50', '50名' ],
				[ '100', '100名' ] ]
	});

	combobox = new Ext.form.ComboBox({
		id : 'topNComboBox',
		store : store,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	combobox.on('select', function(combo, record) {
		reLoadData();
	});

	// sets default value
	var firstValue = store.getRange()[0].data.value;
	combobox.setValue(firstValue);

	return combobox;
}

function tabChange() {
	if (!tabPanelChanged) {
		tabPanelChanged = true;
	} else {
		reLoadData();
	}
}

function reLoadData() {
	if (mainPanel) {
		var ds;
		var type;
		if (mainPanel.activeTab.id == 'dailyPanel') {
			ds = dailyStroe;
			type = 'daily';
		} else if (mainPanel.activeTab.id == 'weekPanel') {
			ds = weekStroe;
			type = 'weekly';
		} else if (mainPanel.activeTab.id == 'monthPanel') {
			ds = monthStroe;
			type = 'monthly';
		} else {
			ds = quarterStroe;
			type = 'quarter';
		}

		var topN = combobox.getValue();
		ds
				.load({
					params : {
						type : type,
						topN : topN
					},
					callback : function(r, options, success) {
						if (r.length == 0) {
							if (success) {
								Ext.MessageBox.alert(TXT_common_hint,
										TXT_search_empty_msg);
								return;
							} else {
								if (ds.reader.responseText == '[null]') {
									Ext.Msg
											.alert(
													TXT_common_hint,
													TXT_common_relogin,
													function() {
														window.location.href = '../eni/common/logout.jsp';
													});
									return;
								} else {
									Ext.MessageBox.alert(TXT_common_hint,
											TXT_SITE_CONFIGURATION_CHECK);
									return;
								}
							}
						}
					}
				});
	}
}

function getDataStroe(type, topN) {
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			fields : [ {
				name : 'rowNo',
				type : 'int'
			}, {
				name : 'keyword'
			}, {
				name : 'searchCount',
				type : 'int'
			}, {
				name : 'lastRowNo',
				type : 'int'
			}, {
				name : 'lastSearchCount',
				type : 'int'
			} ]
		})
	});

	ds.baseParams = {
		cmd : 'searchKeywordHistoryCommand',
		action : 'getTopNKeywordTOJSON'
	};
	ds
			.load({
				params : {
					type : type,
					topN : topN
				},
				callback : function(r, options, success) {
					if (r.length == 0) {
						if (success) {
							Ext.MessageBox.alert(TXT_common_hint,
									TXT_search_empty_msg);
							return;
						} else {
							if (ds.reader.responseText == '[null]') {
								Ext.Msg
										.alert(
												TXT_common_hint,
												TXT_common_relogin,
												function() {
													window.location.href = '../eni/common/logout.jsp';
												});
								return;
							} else {
								Ext.MessageBox.alert(TXT_common_hint,
										TXT_SITE_CONFIGURATION_CHECK);
								return;
							}
						}
					}
				}
			});

	return ds;
}

function getKeyLeaderBoardGrid(dataStroe, type, currRowNoColName,
		keywordColName, currSearchCountColName, lastRowNoColName,
		lastSearchCountColName) {
	var keyCm = new Ext.grid.ColumnModel(
			[
					{
						header : currRowNoColName,
						dataIndex : 'rowNo',
						width : 100,
						renderer : function(rowNo) {
							var record;
							if (type == 'daily') {
								record = dailyStroe.getAt(rowNo - 1);
							} else if (type == 'weekly') {
								record = weekStroe.getAt(rowNo - 1);
							} else if (type == 'monthly') {
								record = monthStroe.getAt(rowNo - 1);
							} else {
								record = quarterStroe.getAt(rowNo - 1);
							}

							var lastRowNo = record.get("lastRowNo");
							if (lastRowNo == 0) {
								return "<div>"
										+ rowNo
										+ "<img src='../images/raise.png'/></div>";
							} else {
								if (lastRowNo - rowNo == 0) {
									return "<div> "
											+ rowNo
											+ "<img src='../images/keep.png'/></div>";
								} else if (lastRowNo - rowNo > 0) {
									return "<div> "
											+ rowNo
											+ "<img src='../images/raise.png'/></div>";
								} else {
									return "<div> "
											+ rowNo
											+ "<img src='../images/decline.png'/></div>";
								}
							}
						}
					},
					{
						header : keywordColName,
						dataIndex : 'keyword',
						width : 250
					},
					{
						header : currSearchCountColName,
						dataIndex : 'searchCount',
						width : 200
					},
					{
						header : lastRowNoColName,
						dataIndex : 'lastRowNo',
						width : 100
					},
					{
						header : lastSearchCountColName,
						dataIndex : 'lastSearchCount',
						width : 200
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Operation + '</div>',
						dataIndex : 'keyword',
						width : 80,
						renderer : function(v) {
							return "<div width='100%' style='text-align:center'><a style='color:blue;text-decoration:underline;cursor:pointer' onClick=showDetails('"
									+ v
									+ "','"
									+ type
									+ "')>"
									+ TXT_common_detail + "</a></div>";
						}
					} ]);

	var keySm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});

	var keyGrid = new Ext.grid.GridPanel({
		border : false,
		region : 'center',
		ds : dataStroe,
		cm : keyCm,
		sm : keySm,
		stripeRows : true,
		autoHeight : true,
		loadMask : {
			msg : 'key loading..'
		}
	});

	return keyGrid;
}

function exportExcelButtonClick() {
	if (!BestvSearch.isSessionTimeOut()) {
		var topN = combobox.getValue();

		window.location.href = '../DispatchServlet?cmd=searchKeywordHistoryCommand&action=createExcel&expExcel=y&topN='
				+ topN + '&flag=' + Math.random();
	} else {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
	}
}

function displayLeaderBoard() {
	combobox = getTopNCombox();
	var topN = combobox.getValue();

	dailyStroe = getDataStroe('daily', topN);
	// Just get daily dataStore, so that, just need send one request to server,
	// For others dataStore, use dailyStore instead when init, and also will be
	// updated when tab changed.
	weekStroe = dailyStroe;
	monthStroe = dailyStroe;
	quarterStroe = dailyStroe;

	var dailyGird = getKeyLeaderBoardGrid(dailyStroe, 'daily', TXT_today
			+ TXT_search_leaderboard_no_label, TXT_search_keyword_label,
			TXT_today + TXT_search_keyword_count, TXT_yesterday
					+ TXT_search_leaderboard_no_label, TXT_yesterday
					+ TXT_search_keyword_count);
	var weekGird = getKeyLeaderBoardGrid(weekStroe, 'weekly', TXT_this_week
			+ TXT_search_leaderboard_no_label, TXT_search_keyword_label,
			TXT_this_week + TXT_search_keyword_count, TXT_last_week
					+ TXT_search_leaderboard_no_label, TXT_last_week
					+ TXT_search_keyword_count);
	var monthGird = getKeyLeaderBoardGrid(monthStroe, 'monthly', TXT_this_month
			+ TXT_search_leaderboard_no_label, TXT_search_keyword_label,
			TXT_this_month + TXT_search_keyword_count, TXT_last_month
					+ TXT_search_leaderboard_no_label, TXT_last_month
					+ TXT_search_keyword_count);
	var quarterGird = getKeyLeaderBoardGrid(quarterStroe, 'quarter',
			TXT_this_quarter + TXT_search_leaderboard_no_label,
			TXT_search_keyword_label, TXT_this_quarter
					+ TXT_search_keyword_count, TXT_last_quarter
					+ TXT_search_leaderboard_no_label, TXT_last_quarter
					+ TXT_search_keyword_count);

	var exportExcelButton = new Ext.Button({
		id : "exportExcelButton",
		text : TXT_search_export_excel_text,
		type : "button",
		handler : exportExcelButtonClick
	});

	mainPanel = new Ext.TabPanel({
		region : 'center',
		activeTab : 0,
		frame : true,
		buttonAlign : 'right',
		layoutOnTabChange : true,
		margins : '0,20,0,0',
		tbar : [ '-', exportExcelButton, '-', '->',
				'&nbsp;&nbsp;&nbsp;&nbsp;前', '-', combobox, '-' ],
		listeners : {
			'tabchange' : tabChange
		},
		items : [ {
			id : 'dailyPanel',
			title : TXT_search_leaderboard_daily_label,
			closable : false,
			autoScroll : true,
			height : 500,
			items : [ dailyGird ]
		}, {
			id : 'weekPanel',
			title : TXT_search_leaderboard_week_label,
			closable : false,
			autoScroll : true,
			items : [ weekGird ]
		}, {
			id : 'monthPanel',
			title : TXT_search_leaderboard_month_label,
			closable : false,
			autoScroll : true,
			items : [ monthGird ]
		}, {
			id : 'quarterPanel',
			title : TXT_search_leaderboard_quarer_label,
			closable : false,
			autoScroll : true,
			items : [ quarterGird ]
		} ]
	});

	BestvSearch.glb_mainPanel.add(mainPanel);
	BestvSearch.drawMainFrame(
			TXT_app_name + '-' + TXT_search_leaderboard_label, null);
}

function showDetails(keyword, type) {
	var chartPanel = getChartPanel(keyword, type);
	var window = new Ext.Window({
		title : keyword + "-" + TXT_search_leaderboard_details_title,
		layout : 'fit',
		width : 950,
		height : 520,
		closeAction : 'hide',
		plain : true,
		modal : true,
		items : [ chartPanel ]
	});
	window.show();
}

function getChartURL(keyword, type) {
	var url = "";
	if (!BestvSearch.isSessionTimeOut()) {
		var conn = Ext.lib.Ajax.getConnectionObject().conn;
		var actionURL = '../DispatchServlet?cmd=searchKeywordHistoryCommand&action=getChartURL&keyword='
				+ keyword + '&type=' + type;

		// Gets month chart
		conn.open("GET", actionURL, false);
		conn.send(null);
		url = conn.responseText;

	} else {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
	}

	return '../' + url;
}

function getChartPanel(keyword, type) {
	var chartPanel = new Ext.TabPanel({
		region : 'center',
		activeTab : 0,
		frame : true,
		buttonAlign : 'right',
		layoutOnTabChange : true,
		listeners : {
			'tabchange' : tabChange
		},
		items : [
				{
					id : 'dailyPanel',
					title : TXT_common_daily_label,
					closable : false,
					autoScroll : true,
					html : '<div><img src="' + getChartURL(keyword, 'daily')
							+ '" /></div>'
				},
				{
					id : 'weeklyPanel',
					title : TXT_common_weekly_label,
					closable : false,
					autoScroll : true,
					html : '<div><img src="' + getChartURL(keyword, 'weekly')
							+ '" /></div>'
				},
				{
					id : 'monthPanel',
					title : TXT_common_monthly_label,
					closable : false,
					autoScroll : true,
					html : '<div><img src="' + getChartURL(keyword, 'monthly')
							+ '" /></div>'
				},
				{
					id : 'quarterPanel',
					title : TXT_common_quarter_label,
					closable : false,
					autoScroll : true,
					html : '<div><img src="' + getChartURL(keyword, 'quarter')
							+ '" /></div>'
				} ]
	});

	if (type == 'daily') {
		chartPanel.setActiveTab('dailyPanel');
	} else if (type == 'weekly') {
		chartPanel.setActiveTab('weeklyPanel');
	} else if (type == 'monthly') {
		chartPanel.setActiveTab('monthPanel');
	} else {
		chartPanel.setActiveTab('quarterPanel');
	}
	return chartPanel;
}

Ext.onReady(displayLeaderBoard);